package org.jeecg.module.flow.meter.tcpserver.tcpServer;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class HexClient {

    public static void main(String[] args) {
        String serverAddress = "localhost";
        int serverPort = 8503;

        try (Socket socket = new Socket(serverAddress, serverPort)) {
            System.out.println("Connected to the server...");

            // 获取输出流
            OutputStream outputToServer = socket.getOutputStream();
            // 获取输入流
            BufferedReader inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 新线程来处理服务器的输入
            Thread receiveThread = new Thread(() -> {
                try {
                    String received;
                    while ((received = inputFromServer.readLine()) != null) {
                        System.out.println("Received from server: " + received);
                    }
                } catch (IOException e) {
                    System.err.println("Error reading from the server: " + e.getMessage());
                    e.printStackTrace();
                }
            });
            receiveThread.start();

            // 从控制台读取用户输入并发送
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("Enter a message (or 'quit' to exit): ");
                String userInput = scanner.nextLine();
                if (userInput.equalsIgnoreCase("quit")) {
                    break;
                }

                byte[] bytes = (byte[]) new Hex().decode(userInput.replace(" ", ""));
                outputToServer.write(bytes);
                outputToServer.flush();

                System.out.println("Message sent.");
            }

            receiveThread.interrupt(); // 停止接收线程
            System.out.println("Client is now disconnected.");
        } catch (IOException e) {
            System.err.println("Error connecting to the server: " + e.getMessage());
            e.printStackTrace();
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
    }
}
